package render

import (
	"cloud-entropy-storage-system/common/pkg/resp"
	"cloud-entropy-storage-system/server/internal/config"
	"cloud-entropy-storage-system/server/internal/core/server"
	"cloud-entropy-storage-system/server/internal/svc"
	"cloud-entropy-storage-system/server/model/metadata"
	"github.com/asdine/storm/v3"
	"github.com/bluele/gcache"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"net/http"
)

type Render struct {
	log     *zap.Logger
	db      *storm.DB
	gc      gcache.Cache
	userSvc *svc.UserSvc
	fileSvc *svc.FileSvc
	cfg     config.Config
}

func NewRender(log *zap.Logger, db *storm.DB, gc gcache.Cache, meta *metadata.MetaData, manager *server.Manager, cfg config.Config) *Render {
	return &Render{
		log:     log,
		db:      db,
		gc:      gc,
		userSvc: svc.NewUserSvc(log, db, gc),
		fileSvc: svc.NewFileSvc(log, meta, manager),
		cfg:     cfg,
	}
}

func (r *Render) Login() gin.HandlerFunc {
	return func(c *gin.Context) {
		resp.BuildTpl(c, "login").WriteTpl()
	}
}

func (r *Render) Logout() gin.HandlerFunc {
	return func(c *gin.Context) {
		if svc.IsSignedIn(c) {
			if err := svc.SignOut(c); err != nil {
				r.log.Error("svc.SignOut", zap.Error(err))
			}
		}
		c.Redirect(http.StatusFound, "/login")
		c.Abort()
	}
}

func (r *Render) Index() gin.HandlerFunc {
	return func(c *gin.Context) {
		if c.Request.RequestURI == "/facicon.ico" {
			return
		}
		resp.BuildTpl(c, "index").WriteTpl()
	}
}
